<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <!-- hexo-inject:begin --><!-- hexo-inject:end --><meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 3.9.0">
<meta name="baidu-site-verification" content="pFajzJd0SZ" />
<meta name="google-site-verification" content="nWFVcb4qcdyxOeW2mwDvLXa4UOsZdsGAH5uKR5PFG_o" />
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">

<link rel="stylesheet" href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic|Roboto Slab:300,300italic,400,400italic,700,700italic|Fira Code:300,300italic,400,400italic,700,700italic&display=swap&subset=latin,latin-ext">
<link rel="stylesheet" href="/lib/font-awesome/css/all.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"jiangchenrui.gitee.io","root":"/","scheme":"Gemini","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":true,"show_result":true,"style":"mac"},"back2top":{"enable":true,"sidebar":true,"scrollpercent":false},"bookmark":{"enable":true,"color":"#222","save":"manual"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":"valine","storage":true,"lazyload":false,"nav":null,"activeClass":"valine"},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="pytorch模型保存和加载">
<meta name="keywords" content="深度学习,笔记">
<meta property="og:type" content="article">
<meta property="og:title" content="pytorch模型保存与加载">
<meta property="og:url" content="https://JiangChenrui.gitee.io/2019/07/23/pytorch模型保存与加载/index.html">
<meta property="og:site_name" content="姜晨瑞的博客">
<meta property="og:description" content="pytorch模型保存和加载">
<meta property="og:locale" content="zh-CN">
<meta property="og:updated_time" content="2021-07-29T01:57:23.166Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="pytorch模型保存与加载">
<meta name="twitter:description" content="pytorch模型保存和加载">

<link rel="canonical" href="https://JiangChenrui.gitee.io/2019/07/23/pytorch模型保存与加载/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>pytorch模型保存与加载 | 姜晨瑞的博客</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript><!-- hexo-inject:begin --><!-- hexo-inject:end -->

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <!-- hexo-inject:begin --><!-- hexo-inject:end --><div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">姜晨瑞的博客</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">记录与总结</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <a role="button" class="book-mark-link book-mark-link-fixed"></a>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://JiangChenrui.gitee.io/2019/07/23/pytorch模型保存与加载/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.jpg">
      <meta itemprop="name" content="JiangChenrui">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="姜晨瑞的博客">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          pytorch模型保存与加载
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2019-07-23 09:51:53" itemprop="dateCreated datePublished" datetime="2019-07-23T09:51:53+08:00">2019-07-23</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2021-07-29 09:57:23" itemprop="dateModified" datetime="2021-07-29T09:57:23+08:00">2021-07-29</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/pytorch/" itemprop="url" rel="index"><span itemprop="name">pytorch</span></a>
                </span>
            </span>

          
            <span id="/2019/07/23/pytorch模型保存与加载/" class="post-meta-item leancloud_visitors" data-flag-title="pytorch模型保存与加载" title="阅读次数">
              <span class="post-meta-item-icon">
                <i class="fa fa-eye"></i>
              </span>
              <span class="post-meta-item-text">阅读次数：</span>
              <span class="leancloud-visitors-count"></span>
            </span>
  
  <span class="post-meta-item">
    
      <span class="post-meta-item-icon">
        <i class="far fa-comment"></i>
      </span>
      <span class="post-meta-item-text">Valine：</span>
    
    <a title="valine" href="/2019/07/23/pytorch模型保存与加载/#valine-comments" itemprop="discussionUrl">
      <span class="post-comments-count valine-comment-count" data-xid="/2019/07/23/pytorch模型保存与加载/" itemprop="commentCount"></span>
    </a>
  </span>
  
  <br>
            <span class="post-meta-item" title="本文字数">
              <span class="post-meta-item-icon">
                <i class="far fa-file-word"></i>
              </span>
                <span class="post-meta-item-text">本文字数：</span>
              <span>3.3k</span>
            </span>
            <span class="post-meta-item" title="阅读时长">
              <span class="post-meta-item-icon">
                <i class="far fa-clock"></i>
              </span>
                <span class="post-meta-item-text">阅读时长 &asymp;</span>
              <span>3 分钟</span>
            </span>
            <div class="post-description"><center>pytorch模型保存和加载</center></div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <p><a href="https://pytorch.apachecn.org/docs/1.0/saving_loading_models.html" target="_blank" rel="noopener">官方文档</a></p>
<h2 id="模型保存相关的三个核心功能"><a href="#模型保存相关的三个核心功能" class="headerlink" title="模型保存相关的三个核心功能"></a>模型保存相关的三个核心功能</h2><p><strong>torch.save:</strong> 将序列化对象保存到磁盘。此函数使用Python的pickle模块进行序列化，使用此模型可以保存如模型、tensor、字典等各种对象。<br><strong>torch.load:</strong> 使用pickle的unpicking功能将pickle对象文件反序列化到内存。此功能还可以有助于设备加载数据。<br><strong>torch.nn.Moudle.load_state_dict:</strong> 使用反序列化函数<em>state_dict</em>来加载模型的参数字典。  </p>
<h2 id="状态字典"><a href="#状态字典" class="headerlink" title="状态字典"></a>状态字典</h2><p>&emsp;&emsp;在pytorch中，<code>torch.nn.Module</code>模型的可学习参数（即权重和偏差）包含在模型的<em>parameters</em>中，（使用<code>model.parameters()</code>可以进行访问）。<em>state_dict</em>仅仅是python字典对象，它将每一层映射到其参数张量。注意，只有具有可学习参数的层（如卷积层、线性层等）的模型才具有<em>state_dict</em>这一项。优化目标<code>torch.optim</code>也有<em>state_dict</em>属性，它包含有关优化器的状态信息，以及使用的超参数。</p>
<h3 id="示例"><a href="#示例" class="headerlink" title="示例"></a>示例</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># Define model</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">TheModelClass</span><span class="params">(nn.Module)</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self)</span>:</span></span><br><span class="line">        super(TheModelClass, self).__init__()</span><br><span class="line">        self.conv1 = nn.Conv2d(<span class="number">3</span>, <span class="number">6</span>, <span class="number">5</span>)</span><br><span class="line">        self.pool = nn.MaxPool2d(<span class="number">2</span>, <span class="number">2</span>)</span><br><span class="line">        self.conv2 = nn.Conv2d(<span class="number">6</span>, <span class="number">16</span>, <span class="number">5</span>)</span><br><span class="line">        self.fc1 = nn.Linear(<span class="number">16</span> * <span class="number">5</span> * <span class="number">5</span>, <span class="number">120</span>)</span><br><span class="line">        self.fc2 = nn.Linear(<span class="number">120</span>, <span class="number">84</span>)</span><br><span class="line">        self.fc3 = nn.Linear(<span class="number">84</span>, <span class="number">10</span>)</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">forward</span><span class="params">(self, x)</span>:</span></span><br><span class="line">        x = self.pool(F.relu(self.conv1(x)))</span><br><span class="line">        x = self.pool(F.relu(self.conv2(x)))</span><br><span class="line">        x = x.view(<span class="number">-1</span>, <span class="number">16</span> * <span class="number">5</span> * <span class="number">5</span>)</span><br><span class="line">        x = F.relu(self.fc1(x))</span><br><span class="line">        x = F.relu(self.fc2(x))</span><br><span class="line">        x = self.fc3(x)</span><br><span class="line">        <span class="keyword">return</span> x</span><br><span class="line"><span class="comment"># Initialize model</span></span><br><span class="line">model = TheModelClass()</span><br><span class="line"></span><br><span class="line"><span class="comment"># Initialize optimizer</span></span><br><span class="line">optimizer = optim.SGD(model.parameters(), lr=<span class="number">0.001</span>, momentum=<span class="number">0.9</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment"># Print model's state_dict</span></span><br><span class="line">print(<span class="string">"Model's state_dict:"</span>)</span><br><span class="line"><span class="keyword">for</span> param_tensor <span class="keyword">in</span> model.state_dict():</span><br><span class="line">    print(param_tensor, <span class="string">"\t"</span>, model.state_dict()[param_tensor].size())</span><br><span class="line"></span><br><span class="line"><span class="comment"># Print optimizer's state_dict</span></span><br><span class="line">print(<span class="string">"Optimizer's state_dict:"</span>)</span><br><span class="line"><span class="keyword">for</span> var_name <span class="keyword">in</span> optimizer.state_dict():</span><br><span class="line">    print(var_name, <span class="string">"\t"</span>, optimizer.state_dict()[var_name])</span><br></pre></td></tr></table></figure>
<p><strong>输出：</strong></p>
<figure class="highlight ruby"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">Model<span class="string">'s state_dict:</span></span><br><span class="line"><span class="string">conv1.weight     torch.Size([6, 3, 5, 5])</span></span><br><span class="line"><span class="string">conv1.bias   torch.Size([6])</span></span><br><span class="line"><span class="string">conv2.weight     torch.Size([16, 6, 5, 5])</span></span><br><span class="line"><span class="string">conv2.bias   torch.Size([16])</span></span><br><span class="line"><span class="string">fc1.weight   torch.Size([120, 400])</span></span><br><span class="line"><span class="string">fc1.bias     torch.Size([120])</span></span><br><span class="line"><span class="string">fc2.weight   torch.Size([84, 120])</span></span><br><span class="line"><span class="string">fc2.bias     torch.Size([84])</span></span><br><span class="line"><span class="string">fc3.weight   torch.Size([10, 84])</span></span><br><span class="line"><span class="string">fc3.bias     torch.Size([10])</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">Optimizer'</span>s <span class="symbol">state_dict:</span></span><br><span class="line">state    &#123;&#125;</span><br><span class="line">param_groups     [&#123;<span class="string">'lr'</span>: <span class="number">0</span>.<span class="number">001</span>, <span class="string">'momentum'</span>: <span class="number">0</span>.<span class="number">9</span>, <span class="string">'dampening'</span>: <span class="number">0</span>, <span class="string">'weight_decay'</span>: <span class="number">0</span>, <span class="string">'nesterov'</span>: False, <span class="string">'params'</span>: [<span class="number">4675713712</span>, <span class="number">4675713784</span>, <span class="number">4675714000</span>, <span class="number">4675714072</span>, <span class="number">4675714216</span>, <span class="number">4675714288</span>, <span class="number">4675714432</span>, <span class="number">4675714504</span>, <span class="number">4675714648</span>, <span class="number">4675714720</span>]&#125;]</span><br></pre></td></tr></table></figure>
<h2 id="保存和加载推断模型"><a href="#保存和加载推断模型" class="headerlink" title="保存和加载推断模型"></a>保存和加载推断模型</h2><h3 id="保存-加载state-dict-推荐使用"><a href="#保存-加载state-dict-推荐使用" class="headerlink" title="保存/加载state_dict(推荐使用)"></a>保存/加载<code>state_dict</code>(推荐使用)</h3><p><strong>保存：</strong></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">torch.save(model.state_dict(), PATH)</span><br></pre></td></tr></table></figure>
<p><strong>加载:</strong></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">model = TheModelClass(*args, **kwargs)</span><br><span class="line">model.load_state_dict(torch.load(PATH))</span><br><span class="line">model.eval()</span><br></pre></td></tr></table></figure>
<p>&emsp;&emsp;用保存的模型进行推断的时候，只需要保存模型学习到的参数，使用<code>torch.save()</code>函数来保存模型<em>state_dict</em>，所用的资源要少于保存完整模型。在进行推断之前，要调用<code>model.eval()</code>去设置dropout和batch normalization层为评估模式。在传入<code>load_state_dict()</code>函数之前，需要使用<code>torch.load()</code>对<em>state_dict</em>进行反序列化。</p>
<h3 id="保存-加载完整模型"><a href="#保存-加载完整模型" class="headerlink" title="保存/加载完整模型"></a>保存/加载完整模型</h3><p><strong>保存：</strong></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">torch.save(model, PATH)</span><br></pre></td></tr></table></figure>
<p><strong>加载：</strong></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">model = torch.load(PATH)</span><br><span class="line">model.eval()</span><br></pre></td></tr></table></figure>
<h3 id="保存torch-nn-DataParallel模型"><a href="#保存torch-nn-DataParallel模型" class="headerlink" title="保存torch.nn.DataParallel模型"></a>保存<code>torch.nn.DataParallel</code>模型</h3><p><strong>保存：</strong></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">model = TheModelClass(*args, **kwargs)</span><br><span class="line">model = torch.nn.DataParallel(model)</span><br><span class="line">torch.save(model.state_dict(), PATH)</span><br></pre></td></tr></table></figure>
<p><strong>加载：</strong></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">model = TheModelClass(*args, **kwargs)</span><br><span class="line">model = torch.nn.DataParallel(model)</span><br><span class="line">model.load_state_dict(torch.load(PATH))</span><br><span class="line">model.eval()</span><br></pre></td></tr></table></figure>
<p><strong>在加载模型继续训练的时候，加载了两次<code>torch.nn.DataParallel</code>，保存的模型进行推断也需要加载两次才能进行推断。可以通过以下方法将保存的模型转化为非DataParallel模式的模型（所有key的名字前去掉modules）</strong></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> collections <span class="keyword">import</span> OrderedDict</span><br><span class="line"><span class="keyword">from</span> efficientnet <span class="keyword">import</span> efficientnet_b0b</span><br><span class="line"><span class="keyword">import</span> torch.nn <span class="keyword">as</span> nn</span><br><span class="line"><span class="keyword">import</span> torch</span><br><span class="line"></span><br><span class="line">model_path = <span class="string">'Result/efficientnet/07-22_13-15-51/1net_params.pkl'</span></span><br><span class="line">state_dict = torch.load(model_path)</span><br><span class="line">new_state_dict = OrderedDict()</span><br><span class="line"></span><br><span class="line"><span class="keyword">for</span> k, v <span class="keyword">in</span> state_dict.items():</span><br><span class="line">    name = k[<span class="number">7</span>:]</span><br><span class="line">    new_state_dict[name] = v</span><br><span class="line"></span><br><span class="line">two_state_dict = OrderedDict()</span><br><span class="line"></span><br><span class="line"><span class="keyword">for</span> k, v <span class="keyword">in</span> new_state_dict.items():</span><br><span class="line">    name = k[<span class="number">7</span>:]</span><br><span class="line">    two_state_dict[name] = v</span><br><span class="line"></span><br><span class="line">net = efficientnet_b0b((<span class="number">224</span>, <span class="number">224</span>), num_classes=<span class="number">1852</span>)</span><br><span class="line">net = nn.DataParallel(net)</span><br><span class="line">net.load_state_dict(new_state_dict)</span><br></pre></td></tr></table></figure>

    </div>

    
    
    
        

<div>
<ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者： </strong>JiangChenrui
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="https://JiangChenrui.gitee.io/2019/07/23/pytorch模型保存与加载/" title="pytorch模型保存与加载">https://JiangChenrui.gitee.io/2019/07/23/pytorch模型保存与加载/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="noopener" target="_blank"><i class="fab fa-fw fa-creative-commons"></i>BY-NC-SA</a> 许可协议。转载请注明出处！
  </li>
</ul>
</div>


      <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/深度学习/" rel="tag"># 深度学习</a>
              <a href="/tags/笔记/" rel="tag"># 笔记</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2019/07/19/EfficientNet/" rel="prev" title="EfficientNet">
      <i class="fa fa-chevron-left"></i> EfficientNet
    </a></div>
      <div class="post-nav-item">
    <a href="/2019/07/29/linux配置多cuda/" rel="next" title="linux配置多cuda">
      linux配置多cuda <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          
    <div class="comments" id="valine-comments"></div>

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#模型保存相关的三个核心功能"><span class="nav-number">1.</span> <span class="nav-text">模型保存相关的三个核心功能</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#状态字典"><span class="nav-number">2.</span> <span class="nav-text">状态字典</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#示例"><span class="nav-number">2.1.</span> <span class="nav-text">示例</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#保存和加载推断模型"><span class="nav-number">3.</span> <span class="nav-text">保存和加载推断模型</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#保存-加载state-dict-推荐使用"><span class="nav-number">3.1.</span> <span class="nav-text">保存/加载state_dict(推荐使用)</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#保存-加载完整模型"><span class="nav-number">3.2.</span> <span class="nav-text">保存/加载完整模型</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#保存torch-nn-DataParallel模型"><span class="nav-number">3.3.</span> <span class="nav-text">保存torch.nn.DataParallel模型</span></a></li></ol></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="JiangChenrui"
      src="/images/avatar.jpg">
  <p class="site-author-name" itemprop="name">JiangChenrui</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">31</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">13</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">28</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/JiangChenrui" title="GitHub → https://github.com/JiangChenrui" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
  </div>


  <div class="links-of-blogroll motion-element">
    <div class="links-of-blogroll-title"><i class="fa fa-link fa-fw"></i>
      Links
    </div>
    <ul class="links-of-blogroll-list">
        <li class="links-of-blogroll-item">
          <a href="https://www.liaoxuefeng.com/" title="https://www.liaoxuefeng.com/" rel="noopener" target="_blank">廖雪峰</a>
        </li>
        <li class="links-of-blogroll-item">
          <a href="https://charlesliuyx.github.io/" title="https://charlesliuyx.github.io/" rel="noopener" target="_blank">遥行</a>
        </li>
        <li class="links-of-blogroll-item">
          <a href="https://redstonewill.com/" title="https://redstonewill.com/" rel="noopener" target="_blank">红色石头</a>
        </li>
    </ul>
  </div>

      </div>
        <div class="back-to-top motion-element">
          <i class="fa fa-arrow-up"></i>
          <span>0%</span>
        </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-mouse"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">JiangChenrui</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-chart-area"></i>
    </span>
      <span class="post-meta-item-text">站点总字数：</span>
    <span title="站点总字数">121k</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
      <span class="post-meta-item-text">站点阅读时长 &asymp;</span>
    <span title="站点阅读时长">1:50</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.org" class="theme-link" rel="noopener" target="_blank">NexT.Gemini</a> 强力驱动
  </div>

        








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>
<script src="/js/utils.js"></script><script src="/js/motion.js"></script>
<script src="/js/schemes/pisces.js"></script>
<script src="/js/next-boot.js"></script><script src="/js/bookmark.js"></script>



  




  <script src="/js/local-search.js"></script>












  

  

  


<script>
NexT.utils.loadComments(document.querySelector('#valine-comments'), () => {
  NexT.utils.getScript('//unpkg.com/valine/dist/Valine.min.js', () => {
    var GUEST = ['nick', 'mail', 'link'];
    var guest = 'nick,mail,link';
    guest = guest.split(',').filter(item => {
      return GUEST.includes(item);
    });
    new Valine({
      el         : '#valine-comments',
      verify     : false,
      notify     : false,
      appId      : 'cUdEljn6k666MrHJYr6FhqSe-gzGzoHsz',
      appKey     : 'yrwQQpoA00WVm649FXM7AKqW',
      placeholder: "Just go go",
      avatar     : 'mm',
      meta       : guest,
      pageSize   : '10' || 10,
      visitor    : true,
      lang       : 'zh-cn' || 'zh-cn',
      path       : location.pathname,
      recordIP   : false,
      serverURLs : ''
    });
  }, window.Valine);
});
</script><!-- hexo-inject:begin --><!-- hexo-inject:end -->

</body>
</html>
